
import os
import json
import datetime

from utils.define import InitJsonData, JSON_PATH, FILE_DATA_PATH
from utils.tools import showMessageBox
from utils.temp_maken2u import make_n2uDict

class ConfigManager:
    def __init__(self, controller):
        self.controller = controller
        self.configPath = JSON_PATH
        self.config = self.load_config()

        self.customers = set()
        for customers in self.config["customers"].values():
            self.customers = self.customers.union(customers)
        self.customers = list(self.customers)
        self.customers.sort()

        self.nameList = set()
        for names in self.config["name2UnitPrice"].values():
            self.nameList = self.nameList.union(names.keys())
        # year_path = os.path.join(FILE_DATA_PATH, str(datetime.datetime.now().year))
        # if not os.path.exists(year_path):
        #     os.mkdir(year_path)

    def __getitem__(self, item):
        return self.config.get(item)

    @property
    def curCustomerFlag(self):
        return self.controller.customer in self.config["specCustomer"] and self.controller.customer or "normal"

    def getpriceFunc(self):
        def getPrice(parent, name):
            return self.config["name2UnitPrice"].get(self.curCustomerFlag).get(name) or []
        return getPrice

    def addCustomer(self, dir, name):
        if name in self.customers:
            showMessageBox("客户已存在")
            return False
        self.customers.append(name)
        self.config["customers"][dir].append(name)
        self.save_config()
        return True

    def setIDCount(self, idCount):
        self.config["IDCount"] = idCount
        self.save_config()
        self.controller.onIDCountChanged(self.config["IDCount"])

    def addIDCount(self):
        self.config["IDCount"] += 1
        self.save_config()
        self.controller.onIDCountChanged(self.config["IDCount"])

    def load_config(self) -> dict:
        try:
            with open(self.configPath, "r", encoding="utf-8") as f:
                return json.load(f)
        except FileNotFoundError:
            return InitJsonData.copy()

    def save_config(self, items=None) -> bool:
        # 新产品直接存入配置 新价格弹窗询问
        if items is not None and len(items) > 0:
            for item in items:
                name = item["name"]
                unitPrice = item["unitPrice"]
                customer = self.curCustomerFlag
                priceList = self.config["name2UnitPrice"].get(customer).get(name)
                if not priceList:
                    self.config["name2UnitPrice"][customer][name] = [unitPrice]
                else:
                    if unitPrice not in priceList:
                        ans = showMessageBox(f"检测到新价格: {name} - {unitPrice} (客户: {self.controller.customer})，是否正确?")
                        if ans:
                            self.config["name2UnitPrice"][customer][name].append(unitPrice)
                        else:
                            showMessageBox("已取消保存，请修改价格后重新保存")
                            return False

        with open(self.configPath, "w", encoding="utf-8") as f:
            json.dump(self.config, f, indent=4, ensure_ascii=False)

        return True
